package com.dao.impl;

import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static SessionFactory sessionFactory;
    private static Logger logger = Logger.getLogger(HibernateUtil.class);  

    public static SessionFactory buildSessionFactory() {
    	 if(sessionFactory != null){
             closeFactory();
         }
        try {
            // Create the SessionFactory from hibernate.cfg.xml
        	logger.info("Create hibernate session factory");
        	sessionFactory = new Configuration().configure().buildSessionFactory();
        	return sessionFactory;
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
        	logger.error("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    
    public static Session openSession() throws HibernateException {
    	logger.info("Session created!");
        return sessionFactory.openSession();
    }
    
    public static void closeFactory() { 
        if (sessionFactory != null) {
            try {
                sessionFactory.close();
                logger.info("Session factory closed!");
            } catch (HibernateException ignored) { 
                logger.error("Couldn't close SessionFactory",
                           ignored);
            }
        }
    }
    
    public static void close(Session session) {
        if (session != null) {
            try {
                session.close();
            } catch (HibernateException ignored) { 
                logger.error("Couldn't close Session", ignored);
            }
        }
    }
    
    public static void rollback(Transaction tx) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (HibernateException ignored) {
            logger.error("Couldn't rollback Transaction", ignored);
        }
    }
        

}